var userId;
var updateUserNameVal = '';
var comnum;
$(function () {
    userId = $.getUrlParam("id");
    //查询角色
    $.ajax({
        url: "../role/getRolesByCompanyNum.htm",
        type: "get",
        async : false,
        cache: false,
        dataType: "json",
        success: function (result) {
            if (result.status == 0) {
                var data = result.data;
                addRoleOptions(data, "#salesmanRoleId");
            }
        }
    });
    
    //获取salesmanComnum信息
    var company = $("#salesmanComnum").val();
    if(!company && typeof(company) != 'undefined'){
    	//当salesmanComnum不为null和undefined时
    	$.ajax({
            url: "../company/getAllCompanyNumAndName.htm",
            cache: false,
            async : false,
            type: "get",
            dataType: "json",
            success: function (result) {
                if (result.status == 0) {
                	var data = result.data;
                	addComnumOptions(data, "#salesmanComnum");
                    return;
                }
            }
        });
    }
    
    //如果是新增用户
    if (userId == 'null') {
        $("#salesmanId").remove();
    } else {	//如果是编辑用户，则回显数据
    	$("#salesmanName").parent().parent(".form-group").remove();	//编辑用户，则把用户名输入框去掉
    	getUserById();	//数据回显
    	//去掉验证密码的规则
        $("#salesmanPwd").removeClass('validate[required,custom[checkPassword]]');
    }
    
    //检测用户名是否被使用
    $.addCustomAjaxValidity(
        {
            "url": '../user/getSalesmanNameCheck.htm',
            "extraData": "username=" + updateUserNameVal,
            "alertssssTextOk":"* ok",
            "alertText": "* 此用户名已被使用",
            "alertTextLoad": "* 正在确认用户名是否被使用，请稍等..."
        }
    );
    //验证
    $('#editSalesmanForm').validationEngine('attach', {
        validationEventTrigger : 'blur',
        promptPosition: 'topRight',
        scroll: false,
        focusFirstField : true,
        onValidationComplete : function (form, valid) {
        	console.log(valid);
            if (valid){
                if (userId == 'null') {
                    addSysUser();
                } else {
                	var pass = $.trim($("#salesmanPwd").val());
                	if(isCheckPass(pass)){
                		modifyUser();
                	}
                }
            }
        }
    });
   
    //省市区三级联动
    $(".form-inline select").change(function(){
	 	var province = $("#province3").val();
	 	var city = $("#city3").val();
	 	var district = $("#district3").val();
	 	var addr = province+""+city+""+district;
	 	$("#address").val(addr);
    });
});

//加载日期控件
laydate.render({
	elem: '#salesmanJoinTime',
	type: 'datetime'
});

//回显数据
function getUserById() {
    $.ajax({
        url: "../user/getSalesmanInfoById.htm",
        cache: false,
        type: "post",
        async : false,
        dataType: "json",
        data : {salesmanId: userId},
        success: function (result) {
        	
        	if(result.status == 0){
        		var data = result.data;
        		$("#editSalesmanForm").formatForm(data,['password']);
        		$("#password").val('');
        	}else{
        		parent.layer.msg('数据异常，显示失败', {icon: 2});
        	}
        }
    });
}

//关闭窗口
function closeForm() {
    var index = parent.layer.getFrameIndex(window.name); //获取窗口索引
    parent.layer.close(index);
}

//修改
function modifyUser(){
    $.ajax({
        url: "../user/modifySalesmanInfo.htm",
        cache: false,
        type: "post",
        dataType: "json",
        data : $("#editSalesmanForm").serialize(),
        beforeSend:function(){var index = layer.load(1, { shade: [0.8,'#ddd']});},
        complete:function(){var index = layer.closeAll("loading");},
        success: function (result) {
            if (result.status == 0) {
                parent.layer.msg(result.message, {icon: 1});
                parent.$table.bootstrapTable('refresh', {url: '../user/getAllSalesmanUser.htm'});
            } else {
                parent.layer.msg(result.message, {icon: 2});
            }
            closeForm();
        }
    });
}

//增加
function addSysUser() {
    $.ajax({
        url: "../user/addToSalesmanInfo.htm",
        cache: false,
        type: "post",
        dataType: "json",
        data: $("#editSalesmanForm").serialize(),
        beforeSend:function(){var index = layer.load(1, { shade: [0.8,'#ddd']});},
        complete:function(){var index = layer.closeAll("loading");},
        success: function (result) {
            if (result.status == 0) {
                parent.layer.msg(result.message, {icon: 1});
                parent.$table.bootstrapTable('refresh', {url: '../user/getAllSalesmanUser.htm'});
            } else {
                parent.layer.msg(result.message, {icon: 2});
            }
            closeForm();
        }
    });
}

//salesmanComnum的下拉列表  追加到option中
function addRoleOptions(data, selectId){
	for(var i=0; i<data.length; i++){
		$(selectId).append('<option value="' + data[i].id + '">' + data[i].descr + '</option>');
	}
}

//salesmanComnum的下拉列表  追加到option中
function addComnumOptions(data, selectId){
	for(var i=0; i<data.length; i++){
		$(selectId).append('<option value="' + data[i].comnumNum + '">' + data[i].comnumName + '</option>');
	}
}

//验证编辑时输入的密码
function isCheckPass(pass){
	if(pass == "" && pass.length == 0){
		return true;
	}
	var passReg = /^[a-zA-Z]([-_a-zA-Z0-9]{5,15})$/;
	var regFlag = passReg.test(pass);
	if(regFlag){
		return true;
	}else{
		parent.layer.msg('密码必须以字母开头，英文、数字、下划线和减号 6-15位', {icon: 2});
		return false;
	}
}